﻿namespace TopHero
{
    public class Game : ILifecycle
    {
        internal readonly ITimeService timeService;
        internal readonly IViewService viewService;

        private readonly World _world;
        public World world => _world;


        public Game(ITimeService timeService, IViewService viewService, IDebugService debugService)
        {
            this.timeService = timeService;
            this.viewService = viewService;
            Debug.SetDebug(debugService);
            Random.Instance.SetSeed(0);
            
            Debug.Log("-----------Game Start-------------");
            _world = new World(this, GameDefine.MAP_WIDTH, GameDefine.MAP_HEIGHT, GameDefine.CELL_NUMX,
                GameDefine.CELL_NUMY, GameDefine.TEST_ROAD_INDEXS);
        }


        public void Update()
        {
            float dt = timeService.DeltaTime();
            TickCounter.Instance.Update(dt);

            int expectFrameCount = TickCounter.Instance.expectFrameCount;
            while (TickCounter.Instance.frameCount < expectFrameCount)
            {
                _world.Update();
                MessageDispatcher.Instance.DispatchDelayedMessages();
                TickCounter.Instance.AddFrameCount();
            }

            TickCounter.Instance.LaterUpdate();
        }

        public void Destroy()
        {
            EntityManager.Instance.Reset();
            MessageDispatcher.Instance.Reset();
            TickCounter.Instance.Reset();
            _world.Destroy();
            
            Debug.Log("-----------Game End-------------");
        }
        
        public void SetTimeScale(float timeScale)
        {
            TickCounter.Instance.SetTimeScale(timeScale);
        }
    }
}